package asteroids.entity.weapon;

import org.apache.log4j.Logger;

import asteroids.engine.GameState;
import asteroids.engine.Utils;
import asteroids.engine.Utils.PolarCoordinate;
import asteroids.entity.GameObject;
import asteroids.entity.Ship;

public class PhotonCrystals extends Weapon
{
    Logger logger = Logger.getLogger(PhotonCrystals.class);

    private PhotonCrystal crystal = null;

    private static double crystalRadius = 3;
    private static double shardRadius = 1.0;
    private static int crystalPower = 6;
    private static int shardPower = 2;
    private static double energyCost = 5;
    private int numShards;

    private static Utils.PolarCoordinate[] payloadShape = Utils.createPolarCircle(crystalRadius);
    private static Utils.PolarCoordinate[] bulletShape = Utils.createPolarCircle(shardRadius);
    private static int payloadSpeed = 200 / Utils.FRAMES_PER_SECOND;
    private static int bulletSpeed = 240 / Utils.FRAMES_PER_SECOND;
    private static int bulletTTL = (int) (.5 * Utils.FRAMES_PER_SECOND);
    private boolean released = true;

    public PhotonCrystals(Ship ship, int payloadSize)
    {
        super(ship, energyCost, 0);
        this.numShards = payloadSize;
    }

    public PhotonCrystals(Ship ship)
    {
        this(ship, 8);
    }

    public boolean FIRE(GameState state)
    {
        boolean fired = false;

        if( canFireYet(state) && (crystal == null || !crystal.isAlive()) && released )
        {
            manageFireControl(state);
            fired = true;
            crystal = new PhotonCrystal(ship.getXPosition(), ship.getYPosition(),
                    ship.getRotation(), payloadSpeed, crystalPower, payloadShape, ship);

            ship.add(crystal);
            released = false;
        }

        return fired;
    }

    public void release()
    {
        if( crystal != null && crystal.isAlive() )
        {
            double degreesPerShot = 360.0 / numShards;
            double currentDir = 0;
            for( int i = 0; i < numShards; i++ )
            {
                ship.add(new Bullet(crystal.getXPosition(), crystal.getYPosition(), currentDir,
                        bulletSpeed, shardPower, bulletTTL, bulletShape, ship));
                currentDir += degreesPerShot;
            }

            crystal.destroy();
            crystal = null;
        }
        released = true;
    }
}

class PhotonCrystal extends Bullet
{
    public PhotonCrystal(double xpos, double ypos, double direction, double speed, double power,
            PolarCoordinate[] shape, Ship ship)
    {
        super(xpos, ypos, direction, speed, power, shape, ship);
        setFriendlyFire(false);
    }

    @Override
    public void collide(GameObject other, double power)
    {
        super.collide(other, power);
        if( !isAlive() )
        {
            // make the twinkling effect
        }
    }
}